#include <func.h>
#define pipe1 "/tmp/pipe1"
#define pipe2 "/tmp/pipe2"

int p0;
int p1;
int p2;
int p3;
void sigFunc(int num)
{
    kill(p0, 9);
    kill(p1, 9);
    kill(p2, 9);
    kill(p3, 9);
}
int main(int argc, char *argv[])
{
    // 创建一片共享内存；
    int shmid = shmget(1000, 4096, IPC_CREAT | 0666);
    ERROR_CHECK(shmid, -1, "shmget");
    int *pid = (int *)shmat(shmid, NULL, 0);
    ERROR_CHECK(pid, (void *)-1, "shmat");
    pid[0] = getpid();
   printf("pid=%d\n",pid[0]);
 
   // while (pid[0] == 0 || pid[1] == 0 || pid[2] == 0 || pid[3] == 0)
   // {
   // }
    p0 = pid[0];
    p1 = pid[1];
    p2 = pid[2];
    p3 = pid[3];
    signal(SIGUSR1, sigFunc);
    mkfifo(pipe1, 0600);
    mkfifo(pipe2, 0600);
    int fdr = open(pipe1, O_RDONLY);
    int fdw = open(pipe2, O_WRONLY);
    printf("创建好了");
    // int semid = semget(10001,1,IPC_CREAT|0600);
    // ERROR_CHECK(semid,-1,"semget");
    // semctl(semid,0,GETVAL);

    // struct sembuf p;
    // struct sembuf v;
    // p.sem_op = 1;
    // p.sem_flg = SEM_UNDO;
    // p.sem_num = semid;
    // v.sem_op = -1;
    // v.sem_flg = SEM_UNDO;
    // v.sem_num = semid;
    char buf[4096] = {0};
    // 添加监听;
    while (1)
    {
        fd_set rdset;
        FD_ZERO(&rdset);
        FD_SET(fdr, &rdset);
        FD_SET(STDIN_FILENO, &rdset);
        struct timeval timeout;
        timeout.tv_sec = 5000;
        timeout.tv_usec = 500000;
        int ret = select(fdr + 1, &rdset, NULL, NULL, &timeout);
        if (ret == 0)
        {
            puts("timeout!");
            continue;
        }
        if (FD_ISSET(fdr, &rdset))
        {
            
            memset(buf, 0, sizeof(buf));
            int ret = read(fdr, buf, sizeof(buf));
            if (ret == 0)
            {
                puts("你是个好人");
                break;
            }

            printf("buf=%s\n", buf);
        }
        if (FD_ISSET(STDIN_FILENO, &rdset))
        {
            memset(buf, 0, sizeof(buf));
            int ret = read(STDIN_FILENO, buf, sizeof(buf));
            if (ret == 0)
            {
                puts("end\n");
                break;
            }
            if(write(fdw, buf, strlen(buf)-1))
            {
                printf("write成功;");
                
            }
            memcpy(pid,buf,strlen(buf)+1);
           
        }
    }

    return 0;
}